<template>
  <div class="danmaku-container" ref="danmakuContainer">
    <transition-group name="danmaku" tag="div" class="danmaku-inner">
      <div
        v-for="danmaku in activeDanmaku"
        :key="danmaku.id"
        class="danmaku-item"
        :style="{
          top: danmaku.top + 'px',
          animationDuration: danmaku.duration + 's',
          opacity: danmaku.opacity
        }"
      >
        {{ danmaku.content }}
      </div>
    </transition-group>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { wishesApi } from '../api/wishes'

const props = defineProps({
  containerHeight: {
    type: Number,
    default: 500
  }
})

const danmakuContainer = ref(null)
const activeDanmaku = ref([])
const wishes = ref([])
let currentIndex = 0
let timer = null

// 获取愿望列表
const fetchWishes = async () => {
  try {
    const res = await wishesApi.getWishesHome()
    console.log('获取到的愿望数据:', res) // 添加日志
    if (res.code === 0 && res.data) {
      wishes.value = res.data.map(wish => ({
        ...wish,
        wishContent: wish.wishContent || wish.content // 确保兼容两种数据格式
      }))
      console.log('处理后的愿望数据:', wishes.value) // 添加日志
      startDanmaku()
    } else {
      // 测试数据
      wishes.value = [
        { id: 1, wishContent: '祝你生日快乐！' },
        { id: 2, wishContent: '愿你永远开心！' },
        { id: 3, wishContent: '生日快乐，天天开心！' },
      ]
      startDanmaku()
    }
  } catch (error) {
    console.error('获取愿望列表失败:', error)
    // 使用测试数据
    wishes.value = [
      { id: 1, wishContent: '祝你生日快乐！' },
      { id: 2, wishContent: '愿你永远开心！' },
      { id: 3, wishContent: '生日快乐，天天开心！' },
    ]
    startDanmaku()
  }
}

// 生成随机高度
const getRandomTop = () => {
  const maxTop = props.containerHeight - 40
  return Math.floor(Math.random() * maxTop)
}

// 生成随机持续时间
const getRandomDuration = () => {
  return 8 + Math.random() * 4 // 8-12秒
}

// 生成随机透明度
const getRandomOpacity = () => {
  return 0.7 + Math.random() * 0.3 // 0.7-1.0
}

// 添加新弹幕
const addDanmaku = () => {
  if (!wishes.value.length || currentIndex >= wishes.value.length) {
    currentIndex = 0
  }

  const wish = wishes.value[currentIndex]
  console.log('添加新弹幕:', wish) // 添加日志

  const danmaku = {
    id: Date.now() + Math.random(),
    content: wish.wishContent,
    top: getRandomTop(),
    duration: getRandomDuration(),
    opacity: getRandomOpacity()
  }

  console.log('创建的弹幕对象:', danmaku) // 添加日志
  activeDanmaku.value.push(danmaku)
  currentIndex++

  // 移除已播放完的弹幕
  setTimeout(() => {
    const index = activeDanmaku.value.findIndex(item => item.id === danmaku.id)
    if (index !== -1) {
      activeDanmaku.value.splice(index, 1)
    }
  }, danmaku.duration * 1000)
}

// 开始播放弹幕
const startDanmaku = () => {
  console.log('开始播放弹幕') // 添加日志
  // 立即添加第一条弹幕
  addDanmaku()
  
  timer = setInterval(() => {
    if (activeDanmaku.value.length < 10) { // 限制最大同时显示数量
      addDanmaku()
    }
  }, 2000) // 每2秒发送一条弹幕
}

onMounted(() => {
  console.log('组件挂载，开始获取愿望') // 添加日志
  fetchWishes()
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.danmaku-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1000;
}

.danmaku-inner {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

.danmaku-item {
  position: absolute;
  white-space: nowrap;
  color: #fff;
  font-size: 18px;
  padding: 6px 12px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  animation: danmaku-move linear forwards;
  transform: translateX(100vw);
  will-change: transform;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(4px);
  -webkit-backdrop-filter: blur(4px);
}

@keyframes danmaku-move {
  from {
    transform: translateX(100vw);
  }
  to {
    transform: translateX(-100%);
  }
}

.danmaku-enter-active,
.danmaku-leave-active {
  transition: opacity 0.5s ease;
}

.danmaku-enter-from,
.danmaku-leave-to {
  opacity: 0;
}
</style>